<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        text-decoration: none;
      }
      body {
        background-color: #f1f1f1;
      }
      a {
        color: #3cf;
        font-size: 24px;
      }
      a:hover {
        color: pink;
      }
      .allShop {
        margin: 20px auto;
        width: 1700px;
        background-color: #fff;
        border: 1px solid #fff;
      }
      #tabShop {
        width: 1700px;
        text-align: center;
        border-collapse: collapse;
        line-height: 50px;
        border-color: pink;
        font-size: 20px;
      }
      #tabShop #td {
        color: skyblue;
        font-size: 25px;
      }
      #tabShop #tb {
        color: pink;
        font-size: 20px;
      }
      .addShop {
        margin: auto;
        background-color: #fff;
        width: 1700px;
        height: 150px;
        line-height: 100px;
        font-weight: 600;
        border: 1px pink solid;
      }
      span {
        font-size: 25px;
      }
      #addBtn {
        position: absolute;
        top: 86px;
        left: 117px;
        width: 150px;
        height: 40px;
        font-size: 23px;
        border: none;
        border-radius: 5px;
        color: black;
        cursor: pointer;
        background-color: pink;
      }
      #addBtn:hover {
        color: #fff;
        background-color: rgb(0, 174, 255);
      }
      #sort {
        border: none;
        cursor: pointer;
        background-color: #fff;
        color: skyblue;
        font-size: 25px;
        font-weight: 600;
      }
      #prices {
        border: none;
        cursor: pointer;
        background-color: #fff;
        color: skyblue;
        font-size: 25px;
        font-weight: 600;
      }
      #search {
        position: absolute;
        top: 88px;
        left: 376px;
        display: block;
        width: 400px;
        height: 35px;
        border: 1px pink solid;
        border-radius: 5px;
      }
    </style>
  </head>
  <body>
    <!-- 添加商品列表 -->
    <div class="addShop">
      <!-- 名称（uname） -->
      <span>商品名称：</span>
      <input id="uname" type="text" placeholder="请输入商品名称" />
      <!-- 库存（stock） -->
      <span>商品库存：</span>
      <input id="stock" type="text" placeholder="请输入库存" />
      <!-- 价格（price） -->
      <span>商品价格：</span>
      <input id="price" type="text" placeholder="请输入商品价格" />
      <!-- 已售（sold） -->
      <span>商品已售：</span>
      <input id="sold" type="text" placeholder="请输入商品已售" />
      <!-- 照片（img） -->
      <span>商品照片：</span>
      <input id="img" type="text" placeholder="请输入商品图片" />
      <!-- 添加按钮（addBtn） -->
      <button id="addBtn">添加</button>
      <input
        id="search"
        type="search"
        onchange="search()"
        placeholder="请输入商品名称"
      />
    </div>
    <!-- 商品列表 -->
    <div class="allShop">
      <h1 style="text-align: center">商品列表</h1>
      <table border="1" id="tabShop">
        <thead id="td">
          <tr>
            <th><input id="all" type="checkbox" />全选</th>
            <th><button id="sort" onclick="sort()">排序</button></th>
            <th>商品图片</th>
            <th>商品名称</th>
            <th><button id="prices" onclick="price()">价格</button></th>
            <th>库存</th>
            <th>实际销量</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody id="tbbb"></tbody>
      </table>
    </div>
    <script>
      var index = localStorage.getItem("index")
        ? Number(localStorage.index)
        : 1;
      //  页面加载完毕获得
      window.onload = function () {
        showShops();
        // 添加商品绑定事件
        document.getElementById("addBtn").onclick = addShopbtn;
        // 全选按钮绑定事件
        document.getElementById("all").onchange = allCheck;
      };
      // 添加商品
      function addShopbtn() {
        var uname = document.getElementById("uname");
        var stock = document.getElementById("stock");
        var price = document.getElementById("price");
        var sold = document.getElementById("sold");
        var img = document.getElementById("img");
        // 内容不能为空
        if (!uname || !stock || !price || !sold || !img) {
          alert("请填写完整信息");
          return;
        }
        var data = {
          id: index++,
          goods_name: uname.value,
          stock: stock.value,
          price: price.value,
          sold: sold.value,
          img: img.value,
          addtime: time(),
          status: false,
        };
        // 向本地存储添加序号
        localStorage.setItem("index", index);
        setDate("data", data);
        showShops();
        // 清空输入框
        uname.value = stock.value = price.value = sold.value = img.value = "";
      }
      // 添加
      function setDate(key, value) {
        let data = getDate(key);
        data.push(value);
        localStorage.setItem(key, JSON.stringify(data));
      }
      // 获取判断
      function getDate(key) {
        //判断本地存储是否有值，没有就创建一个
        return localStorage.getItem(key)
          ? JSON.parse(localStorage.getItem(key))
          : [];
      }
      // 全选
      function allCheck() {
        var data = getDate("data");
        // 获取全选按钮状态
        var allStatus = this.checked;

        data.map(function (item) {
          // 将全选按钮状态给每个元素
          item.status = allStatus;
        });
        localStorage.setItem("data", JSON.stringify(data));
        showShops();
      }
      // 小按钮
      function checkStatus(index) {
        var data = getDate("data");
        data[index].status = !data[index].status;
        localStorage.setItem("data", JSON.stringify(data));
        showShops();
      }
      // 显示所有商品
      function showShops() {
        var data = getDate("data");
        //渲染dom
        var tbodyHtml = "";
        for (let i = 0; i < data.length; i++) {
          tbodyHtml += `
                <tr>
                  <td><input id="" type="checkbox" {
            ${data[i].status ? "checked" : ""}></td>
                  <td>${data[i].id}</td>
                  <td><img src='${
                    data[i].img
                  }' width="200px" height="150px"/></td>
                  <td>${data[i].goods_name}</td>
                  <td>${data[i].price} ￥</td>
                  <td>${data[i].stock}</td>
                  <td>${data[i].sold}</td>
                  <td>${data[i].addtime}</td>
                  <td>
                    <a href='# 'onclick="del(${i})">删除</a>
                    <a href="#" onclick="copy(${i})">复制</a>
                      </td>
                </tr>
              `;
        }
        document.getElementById("tbbb").innerHTML = tbodyHtml;
      }
      // 删除
      function del(id) {
        var data = getDate("data");
        data.splice(id, 1);
        localStorage.setItem("data", JSON.stringify(data));
        showShops();
      }
      // 排序
      function sort() {
        var data = getDate("data");
        data.sort(function (a, b) {
          return b.id - a.id;
        });
        localStorage.setItem("data", JSON.stringify(data));
        showShops();
      }
      // 价格
      function price() {
        var data = getDate("data");
        data.sort(function (a, b) {
          return b.price - a.price;
        });
        localStorage.setItem("data", JSON.stringify(data));
        showShops();
      }
      //封装时间
      function time() {
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth();
        let date1 = date.getDate();
        let hour = date.getHours();
        let min = date.getMinutes();
        let sec = date.getSeconds();
        let currentTime = `${year}-${month}-${date1}<br>${hour}:${min}:${sec}`;
        return currentTime;
      }
      // 复制
      function copy(index) {
        var data = getDate("data");
        var data = {
          id: data[index].id,
          goods_name: data[index].goods_name,
          stock: data[index].stock,
          price: data[index].price,
          sold: data[index].sold,
          img: data[index].img,
          addtime: data[index].addtime,
          status: data[index].status,
        };
        setDate("data", data);
        showShops();
      }
      // 搜索
      function search() {
        var data = getDate("data");
        var seaVal = document.getElementById("search");
        var tbodyHtml = "";
        data.map(function (item, index) {
          if (item.goods_name == seaVal.value) {
            tbodyHtml += `
            <tr>
                  <td><input id="" type="checkbox" {
            ${item.status ? "checked" : ""}></td>
                  <td>${item.id}</td>
                  <td><img src='${item.img}' width="200px" height="150px"/></td>
                  <td>${item.goods_name}</td>
                  <td>${item.price} ￥</td>
                  <td>${item.stock}</td>
                  <td>${item.sold}</td>
                  <td>${item.addtime}</td>
                  <td>
                    <a href='# 'onclick="del(${index})" id="${item.id}">删除</a>
                    <a href="#" onclick="copy(${index})">复制</a>
                      </td>
                </tr>
              `;
          }
          document.getElementById("tbbb").innerHTML = tbodyHtml;
        });
        if (seaVal.value == "") {
          showShops();
        }
      }
    </script>
  </body>
</html>
